package com.lemon.reggie.common;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;
import org.springframework.web.multipart.support.MissingServletRequestPartException;
import org.springframework.web.servlet.NoHandlerFoundException;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.stream.Collectors;

@Component
@RestControllerAdvice
@Slf4j
@SuppressWarnings("rawtypes")
public class GlobalExceptionHandle {

    /**
     * 全局异常
     * @param e Exception
     * @return
     */
    //当controller层中抛出Exception，则捕获
    //@ExceptionHandler(Exception.class)
    //设置响应状态码为500
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R handleException(Exception e) {
        log.error(e.getMessage(),e);
        return R.error("服务器内部错误！");
    }

    /**
     * 捕获自定义异常
     * @param e BusinessException
     * @return
     */
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(BusinessException.class)
    public R handleBusinessException(BusinessException e) {
        log.error(e.getMessage(), e);
        return R.error(e.getMessage());
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R handleSQLIntegrityConstraintViolationException(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage(), e);
        //Duplicate entry '川菜' for key 'idx_category_name
        if (e.getMessage().contains("Duplicate entry")) {
            return R.error(e.getMessage().split(" ")[2] + "已存在，请重新输入！");
        }
        return R.error("服务器内部错误！");
    }

    @ExceptionHandler(IOException.class)
    public R handleIOException(IOException e) {
        log.error(e.getMessage(), e);
        if (e.getMessage().contains("FileNotFoundException")) {
            return R.error("上传图片目录不存在！");
        }
        return R.error("上传图片失败！");
    }

    /**
     * @param e 对validation校验异常进行处理
     * @return com.lemon.reggie.common.R
     * @author Guannankun
     * @since 2021/8/12
     */
    //@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public R handleValidationException(MethodArgumentNotValidException e) {

        List<FieldError> fieldErrorList = e.getBindingResult().getFieldErrors();
        //FieldError fieldError = e.getBindingResult().getFieldError();
        if (CollectionUtils.isNotEmpty(fieldErrorList)) {
            String message =
                    fieldErrorList.stream().map(FieldError::getDefaultMessage).collect(Collectors.joining(System.getProperty("line.separator")));
            log.error(e.getMessage(), e);
            return R.error(message);
        } else {
            log.error(e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }

}
